package com.lpc.framework.web.resolver;

import javax.naming.directory.NoSuchAttributeException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.lpc.framework.util.JsonUtil;
import com.lpc.framework.web.annoation.QueryString;

/**
 * 自动传入SessionModel
 * 
 * @author jiangjinlong
 *
 */
public class QueryStringArgumentResolver implements HandlerMethodArgumentResolver {

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.web.method.support.HandlerMethodArgumentResolver#supportsParameter(org.springframework.core
     * .MethodParameter)
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(QueryString.class);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.web.method.support.HandlerMethodArgumentResolver#resolveArgument(org.springframework.core
     * .MethodParameter, org.springframework.web.method.support.ModelAndViewContainer,
     * org.springframework.web.context.request.NativeWebRequest,
     * org.springframework.web.bind.support.WebDataBinderFactory)
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        QueryString queryString = parameter.getParameterAnnotation(QueryString.class);
        String parm = request.getParameter(queryString.key());
        if (StringUtils.isEmpty(parm)) {
            throw new NoSuchAttributeException("缺少" + queryString.key() + "参数");
        }
        Class<?> clz = parameter.getParameterType();
        return JsonUtil.json2Object(parm, clz);
    }

}
